//
//  CompleteDataTableVC.m
//  Cunli
//
//  Created by lilubin on 15/7/22.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "CompleteDataTableVC.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "Config.h"
#import "SettingTableViewCell.h"
#import "User.h"
#import "MainTabbarVC.h"
#import "MMDrawerController.h"
#import "SidePersonMenuVC.h"
/*
#import "PersonalPortraitCell.h"
#import "Utils.h"
#import "UIImage+MultiFormat.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImage+fixOrientation.h"
 */
#import "DeviceInfoClass.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define KCLLOGINCHANGE @"myloginchange"
//#define KCLPORTRAITCHANGE @"portraitChanged"
#define baseTextFieldTag 200

typedef NS_ENUM(int, AreaDataType)
{
    AreaDataTypeProvince = 0,   //省
    AreaDataTypeCity,           //市
    AreaDataTypeCounty,         //县
    AreaDataTypeTown,           //镇
    AreaDataTypeVillage,        //村
};


static NSString *kSettingCellID = @"SettingTableViewCell";

@interface CompleteDataTableVC () <UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    NSString *_userCareer;                  //记录user的career，用来设置信息参数
    NSString *_userAreaID;                  //记录user的家乡信息，用来设置信息参数
    NSString *_userGender;                  //记录user的性别，1＝男， 2＝女
    NSString *_userTrueName;                //记录user的真实姓名
    NSString *_userName;                    //记录user的用户名
    NSString *_userID;
    
    NSMutableArray *_provinceDatasArray;    //省数据存放数组
    NSMutableArray *_cityDatasArray;        //城市数据存放数组
    NSMutableArray *_countyDatasArray;      //县数据存放数组
    NSMutableArray *_townDatasArray;        //镇数据存放数组
    NSMutableArray *_villageDatasArray;     //村数据存放数组
    
    NSString *_tempAreaids;                 //暂时存放地区ids
    NSString *_tempProvinceID;              //暂存省的id
    NSString *_tempCityID;                  //暂存市的id
    NSString *_tempCountyID;                //暂存县的id
    NSString *_tempTownID;                  //暂存镇的id
    NSString *_tempVillageID;               //暂存存的id
    NSString *_tempProvinceName;            //暂存省的名字
    NSString *_tempCityName;                //暂存市的名字
    NSString *_tempCountyName;              //暂存县的名字
    NSString *_tempTownName;                //暂存镇的名字
    NSString *_tempVillageName;             //暂存存的名字
    
    NSString *_tempAreaName1;               //存储省，市，县名称，用于显示在输入框1
    NSString *_tempAreaName2;               //存储镇，村名称，用于显示在输入框2
    
    BOOL _provinceHaveTouched;              //省市县第一次点击
    BOOL _villageHaveTouched;               //村第一次点击
    
//    UIImage *_imageToUpload;                //  上传的图片
    
}
@property (nonatomic, strong) UIPickerView *careerPickerView;           //选择职业

@property (nonatomic, strong) UIPickerView *firstLocationPickerView;    //选择“省，市，县”
@property (nonatomic, strong) UIPickerView *secondLocationPickerView;   //选择“镇，村”
@property (nonatomic, strong) UIPickerView *genderPickerView;           //选择性别
@property (nonatomic, strong) NSArray *careerArray;                     //存储返回的“list”中的数据
@property (nonatomic, strong) NSArray *village;                         //“村”数据数组
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *areaURL;
@property (nonatomic, strong) NSString *areaResponse;

@end

@implementation CompleteDataTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
#pragma mark - 测试时使用
//        _access_token = [Config getOwnSession];
//        _is_invint = @"1";
#pragma end
    
    _areaURL = [_is_invint boolValue]?@"area_all.php":@"area.php";
    _areaResponse = [_is_invint boolValue]?@"area_all":@"area";
    
    
    _provinceHaveTouched = NO;
    _villageHaveTouched = NO;
    [self setNavAttributes];
    [self initAllGlobalParams];
    [self initAllPickerView];
//    [self addTapRecoginzer];
    [self reloadCareerData];
    [self loadAreaDataWithAreaID:@"-1" andDataType:AreaDataTypeProvince];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initAllGlobalParams
{
    _userGender = @"1";
    _provinceDatasArray = [NSMutableArray array];
    _cityDatasArray = [NSMutableArray array];
    _countyDatasArray = [NSMutableArray array];
    _townDatasArray = [NSMutableArray array];
    _villageDatasArray = [NSMutableArray array];
    _tempAreaids = [NSString string];
    _userName = [Config getOwnUsername];
    _userID = [Config getOwnUserID];
}

- (void)setNavAttributes
{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStyleGrouped];
    _tableView.delegate     = self;
    _tableView.dataSource   = self;
    _tableView.bounces      = YES;
    [self.view addSubview:_tableView];
    
    [_tableView setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    
    UIImageView *navBgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [navBgImgView setImage:[UIImage imageNamed:@"NavigationBgImage"]];
    [self.view addSubview:navBgImgView];
    
    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    [navLabel setText:@"完善资料"];
    [navLabel setTextColor:[UIColor whiteColor]];
    [navLabel setFont:[UIFont boldSystemFontOfSize:19]];
    navLabel.textAlignment = NSTextAlignmentCenter;
    [navBgImgView addSubview:navLabel];
    
    if (self.haveLogin.length == 0) {
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame = CGRectMake(8, 27, 30, 30);
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [backBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:backBtn];
    }
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(kScreenWidth-72, 27, 65, 30);
    [nextBtn setTitle:@"完成" forState:UIControlStateNormal];
    nextBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:nextBtn];
    
 
    [self.view setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:kSettingCellID owner:self options:nil].lastObject;
    [self addTapRecoginzerToView:cell];
    /*
    if (indexPath.section == 0) {
            PersonalPortraitCell *portraitCell = [[NSBundle mainBundle] loadNibNamed:@"PersonalPortraitCell" owner:nil options:nil].lastObject;
            return portraitCell;
    }
    else
    {
     */
        switch (indexPath.row) {
            case 0:
            {
                cell.titleLabel.text = @"真实姓名：";
                cell.textField.placeholder = @"不能超过8个汉字";
                cell.textField.delegate = self;
                break;
            }
            case 1:
            {
                cell.titleLabel.text = @"性别：";
                cell.textField.placeholder = @"请选择";
                cell.textField.inputView = _genderPickerView;
                cell.textField.tag = baseTextFieldTag+1;
                cell.textField.delegate = self;
                break;
            }
            case 2:
            {
                cell.titleLabel.text = @"我的职业：";
                cell.textField.placeholder = @"选择职业";
                cell.textField.inputView = _careerPickerView;
                cell.textField.tag = baseTextFieldTag+2;
                cell.textField.delegate = self;
                break;
            }
            case 3:
            {
                cell.titleLabel.text = @"户口地址：";
                cell.textField.placeholder = @"省 市 县";
                cell.textField.inputView = _firstLocationPickerView;
                cell.textField.tag = baseTextFieldTag+3;
                cell.textField.delegate = self;
                break;
            }
            case 4:
            {
                cell.titleLabel.hidden = YES;
                cell.textField.placeholder = @"镇 村";
                cell.textField.inputView = _secondLocationPickerView;
                cell.textField.tag = baseTextFieldTag+4;
                cell.textField.delegate = self;
                break;
            }
            default:
                break;
        }
//    }
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
    if (indexPath.section == 0) {
        return 80;
    }
     */
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel *promtLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    promtLabel.text = @"   提示:村里是一个真实的农村社交网络,请使用真实姓名注册。";
    promtLabel.numberOfLines = 0;
    promtLabel.font = [UIFont systemFontOfSize:14];
    promtLabel.backgroundColor = [UIColor clearColor];
    return promtLabel;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60;
}

/*
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        [self resignTheKeyboard];
        [self choseImageUpload];
    }
}
*/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView                                              // any offset changes
{
    [self resignTheKeyboard];
}

- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)nextAction
{    
//    [self.view endEditing:YES];
    [self resignTheKeyboard];
    if (![_is_invint boolValue]) //不是被邀请的 1:是 0:不是
    {
        if (_tempVillageID.length == 0)
        {
            [Config showHUDWithText:@"请完善地址信息" andImage:@"error"];
            return;
        }
        else
        {
            _userAreaID = [NSString stringWithFormat:@"%@,%@,%@,%@,%@", _tempProvinceID, _tempCityID, _tempCountyID, _tempTownID, _tempVillageID];
        }
    }
    else  //是被邀请的
    {
        if (_tempVillageID.length != 0)
        {
            _userAreaID = [NSString stringWithFormat:@"%@,%@,%@,%@,%@", _tempProvinceID, _tempCityID, _tempCountyID, _tempTownID, _tempVillageID];
        }
        else
        {
            if (_tempTownName.length != 0)
            {
                _userAreaID = [NSString stringWithFormat:@"%@,%@,%@,%@", _tempProvinceID, _tempCityID, _tempCountyID, _tempTownID];
            }
            else
            {
                if (_tempCountyID.length != 0) {
                    _userAreaID = [NSString stringWithFormat:@"%@,%@,%@", _tempProvinceID, _tempCityID, _tempCountyID];
                }
                else
                {
                    if (_tempCityID.length != 0) {
                        _userAreaID = [NSString stringWithFormat:@"%@,%@", _tempProvinceID, _tempCityID];
                    }
                    else
                    {
                        if (_tempProvinceID.length == 0)
                        {
                            [Config showHUDWithText:@"请完善地址信息" andImage:@"error"];
                            return;
                        }else
                        {
                            _userAreaID = [NSString stringWithFormat:@"%@", _tempProvinceID];
                        }
                    }
                }
            }
        }
    }
    
    SettingTableViewCell *cell1 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    if (_userName.length != 0 && cell1.textField.text.length != 0 && _userGender.length != 0 && _userCareer.length != 0 && _userAreaID.length != 0)
    {
        NSMutableDictionary *userInfoDic = [NSMutableDictionary dictionaryWithCapacity:6];
        
        [userInfoDic setObject:_userName forKey:@"username"];
        [userInfoDic setObject:cell1.textField.text forKey:@"truename"];
        [userInfoDic setObject:_userCareer forKey:@"career"];
        [userInfoDic setObject:_userGender forKey:@"gender"];
        [userInfoDic setObject:_userAreaID forKey:@"areaids"];
        
        [userInfoDic setObject:[NSString getSignFromParam:userInfoDic andSession:_access_token] forKey:@"sign"];
        
        [MyDataService requestURL:@"regdetail.php" httpMethod:@"POST" params:userInfoDic fileDatas:nil complection:^(id result) {
            NSLog(@"Regdetail result:%@", result);
            NSString *responseStr = [result objectForKey:@"response"];
            
            if ([responseStr isEqualToString:@"regdetail"])
            {
                [Login doLogin:result[@"userinfo"]];
                [Config saveAutoLogin:YES];
                [Config saveLogintimes:@"1"];
                [self getUserDetailData];
                [self pushToMainVC];
            }
            else
            {
                NSDictionary *errorDic = [result objectForKey:@"error"];
                NSString *errorStr = [errorDic objectForKey:@"text"];
                [self showHUDWithText:errorStr andImage:@"error"];
            }
            
            } failureAction:^{
            [Config showHUDWithText:@"网络错误" andImage:@"error"];
        }];
    }
    else
    {
        [Config showHUDWithText:@"信息不完善" andImage:@"error"];
    }
}

- (void)reloadCareerData
{
    NSMutableDictionary *careerParams = [NSMutableDictionary dictionaryWithCapacity:2];
    [careerParams setObject:_userID forKey:@"userid"];
    NSString *sign = [NSString getSignFromParam:careerParams andSession:_access_token];
    [careerParams setObject:sign forKey:@"sign"];
    
    [MyDataService requestURL:@"career.php" httpMethod:@"GET" params:careerParams fileDatas:nil complection:^(id result) {
        
        if ([result[@"response"] isEqualToString:@"career"])
        {
            self.careerArray = [result objectForKey:@"list"];
        }
        else
        {
            [Config showHUDWithText:@"职业数据请求错误" andImage:@"error"];
        }
        NSLog(@"Career result: %@", result);
    } failureAction:^{
        [Config showHUDWithText:@"网络连接错误" andImage:@"error"];
    }];
}

- (void)initAllPickerView
{
    /*
     NSIndexPath *selIndexPath = [NSIndexPath indexPathForRow:4 inSection:0];
     CGRect rectInTableView = [_tableView rectForRowAtIndexPath:selIndexPath];
     CGPoint point = [_tableView convertPoint:rectInTableView.origin toView:self.view];
     //    textFieldPosition=point.y+rectInTableView.size.height+64;
     */
    CGFloat pickerHeight = 180;
    if ([DeviceInfoClass getCurrentDeviceDetailVersion] == DeviceInfoVersioniPhone4s) {
        pickerHeight = 124;
    }
 
    CGFloat pickerWidth = kScreenWidth - 40;
    CGFloat pickerPositionY = kScreenHeight - 200;
    UIColor *pickerViewBgColor = [UIColor colorWithHexString:UIBgColorValue];
    //初始化选择职业的pickerView
    _careerPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, pickerPositionY, pickerWidth, pickerHeight)];
    _careerPickerView.delegate = self;
    _careerPickerView.dataSource = self;
    _careerPickerView.backgroundColor = pickerViewBgColor;
    _careerPickerView.tag = 101; //职位picker的tag值
    
    //初始化选择“省，市，县”的pickerview
    _firstLocationPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, pickerPositionY, pickerWidth, pickerHeight)];
    _firstLocationPickerView.delegate = self;
    _firstLocationPickerView.dataSource = self;
    _firstLocationPickerView.backgroundColor = pickerViewBgColor;
    _firstLocationPickerView.userInteractionEnabled = YES;
    _firstLocationPickerView.tag = 102; //职位picker的tag值
    
    //初始化选择“镇，村”的pickerview
    _secondLocationPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, pickerPositionY, pickerWidth, pickerHeight)];
    _secondLocationPickerView.delegate = self;
    _secondLocationPickerView.dataSource = self;
    _secondLocationPickerView.backgroundColor = pickerViewBgColor;
    _secondLocationPickerView.tag = 103; //职位picker的tag值
    
    //初始化选择性别的pickerview
    
    _genderPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(20, pickerPositionY, pickerWidth, pickerHeight)];
    _genderPickerView.delegate = self;
    _genderPickerView.dataSource = self;
    _genderPickerView.backgroundColor = pickerViewBgColor;
    _genderPickerView.tag = 104; //职位picker的tag值x
}

#pragma -mark dataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (pickerView.tag == 102) {
        return 3;
    }else if (pickerView.tag == 104)
    {
        return 1;
    }
    return 2;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    //职业选择
    if (pickerView.tag == 101) {
        
        if (component == 0)
        {
            return self.careerArray.count;
        }
        
        NSInteger selCareer = [pickerView selectedRowInComponent:0];
        
        NSDictionary *selectedCareerDic = self.careerArray[selCareer];
        
        NSArray *childCareer = [selectedCareerDic objectForKey:@"child"];
        
        return childCareer.count;
        
    }
    //“省，市，县”选择
    else if(pickerView.tag == 102)
    {
        if (component == 0) {
            return _provinceDatasArray.count;
        }
        else if(component == 1)
        {
            return _cityDatasArray.count;
        }
        else if(component == 2)
        {
            return _countyDatasArray.count;
        }
        return 1;
    }
    //“镇，村”选择
    else if(pickerView.tag == 103)
    {
        if (component == 0) {
            return _townDatasArray.count;
        }
        else
        {
            return _villageDatasArray.count;
        }
    }
    
    return 2;
}

#pragma -mark delegate

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (pickerView.tag == 102)
    {
        return (kScreenWidth - 20)*1.0 / 3;
    }else if(pickerView.tag == 104)
    {
        return kScreenWidth;
    }
    return (kScreenWidth - 20)*1.0 / 2;
    
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == 101) {
        
        if (component == 0) {
            NSDictionary *careerDic = self.careerArray[row];
            NSString *parentName = [careerDic objectForKey:@"name"];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            return parentName;
        }
        else
        {
            NSInteger selCareer = [pickerView selectedRowInComponent:0];
            NSDictionary *careerDic2 = self.careerArray[selCareer];
            if (careerDic2.count != 0)
            {
                NSArray *childCareerArray = [careerDic2 objectForKey:@"child"];
                NSInteger selRow = row;
                if (row > childCareerArray.count-1) {
                    selRow = childCareerArray.count-1;
                }
                NSString *childCareer = [childCareerArray[selRow] objectForKey:@"name"];
                return childCareer;
            }
        }
        return @"";
    }
    //“省，市，县”选择，目前开放地区为“浙江 绍兴 上虞区”
    else
        if(pickerView.tag == 102)
        {
            if (component == 0) {
                //省
                NSDictionary *dic = _provinceDatasArray[row];
                NSString *proName = dic[@"areaname"];
                return proName;
            }
            else if(component == 1)
            {
                //市
                NSDictionary *dic2 = _cityDatasArray[row];
                NSString *cityName = dic2[@"areaname"];
                return cityName;
            }
            else
            {
                //县
                NSDictionary *dic3 = _countyDatasArray[row];
                NSString *countyName = dic3[@"areaname"];
                return countyName;
            }
        }
        else if(pickerView.tag == 103)
        {
            if (component == 0)
            {
                //镇
                NSDictionary *dic4 = _townDatasArray[row];
                NSString *townName = dic4[@"areaname"];
                return townName;
                
            }
            else
            {
                //村
                NSDictionary *dic5 = _villageDatasArray[row];
                NSString *villageName = dic5[@"areaname"];
                return villageName;
                
            }
        }
        else if(pickerView.tag == 104)
        {
            if (row == 0) {
                return @"男";
            }
            return @"女";
        }
    
    return @"";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    SettingTableViewCell *cell2 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    SettingTableViewCell *cell3 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    SettingTableViewCell *cell4 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    SettingTableViewCell *cell5 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    
    if (pickerView.tag == 101) //选择职业
    {
        if (component == 0)
        {
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView reloadComponent:1];
            if (self.careerArray.count != 0)
            {
                NSInteger selCareer1 = [pickerView selectedRowInComponent:0];
                NSDictionary *careerDic = self.careerArray[selCareer1];
                NSString *careerName1 = careerDic[@"name"];
                NSArray *childCareerArray = careerDic[@"child"];
                //                NSInteger selCareer2 = [pickerView selectedRowInComponent:1];
                if (childCareerArray.count != 0)
                {
                    NSDictionary *childCareerDic = childCareerArray[0];
                    NSString *careerName2 = childCareerDic[@"name"];
                    _userCareer = childCareerDic[@"id"];
                    NSString *careerName = [NSString stringWithFormat:@"%@ %@", careerName1, careerName2];
                    cell3.textField.text = careerName;
                }
                else
                {
                    cell3.textField.text = careerName1;
                    _userCareer = careerDic[@"id"];
                }
            }
        }
        if (component == 1)
        {
            if (self.careerArray.count != 0)
            {
                NSInteger selCareer1 = [pickerView selectedRowInComponent:0];
                NSDictionary *careerDic = self.careerArray[selCareer1];
                NSString *careerName1 = careerDic[@"name"];
                NSArray *childCareerArray = careerDic[@"child"];
                NSInteger selCareer2 = [pickerView selectedRowInComponent:1];
                if (childCareerArray.count != 0)
                {
                    NSDictionary *childCareerDic = childCareerArray[selCareer2];
                    NSString *careerName2 = childCareerDic[@"name"];
                    _userCareer = childCareerDic[@"id"];
                    NSString *careerName = [NSString stringWithFormat:@"%@ %@", careerName1, careerName2];
                    cell3.textField.text = careerName;
                }
                else
                {
                    cell3.textField.text = careerName1;
                    _userCareer = careerDic[@"id"];
                }
            }
            else
            {
                return;
            }
        }
        
    }
    else if(pickerView.tag == 102) //选择住址：省，市，县
    {
        if (component == 0) {
            if (_provinceDatasArray.count == 0) {
                return;
            }
            NSDictionary *provinceDic = _provinceDatasArray[row];
            _tempProvinceName = provinceDic[@"areaname"];
            _tempProvinceID = provinceDic[@"areaid"];
            
            if (_cityDatasArray.count != 0) {
                [_cityDatasArray removeAllObjects];
            }
//            [pickerView selectRow:0 inComponent:1 animated:YES];
            [self loadAreaDataWithAreaID:_tempProvinceID andDataType:AreaDataTypeCity];
            cell4.textField.text = _tempProvinceName;
        }
        else if(component == 1)
        {
            NSInteger selRow = row;
            if (_cityDatasArray.count == 0) {
                selRow = 0;
                return;
            }else
            {
                if (row > _cityDatasArray.count-1) {
                    selRow=_cityDatasArray.count;
                }
                NSDictionary *cityDic = _cityDatasArray[selRow];
                _tempCityName = cityDic[@"areaname"];
                _tempCityID = cityDic[@"areaid"];
                if (_countyDatasArray.count != 0) {
                    [_countyDatasArray removeAllObjects];
                }
//                [pickerView selectRow:0 inComponent:2 animated:YES];
                [self loadAreaDataWithAreaID:_tempCityID andDataType:AreaDataTypeCounty];
                cell4.textField.text = [NSString stringWithFormat:@"%@%@", _tempProvinceName, _tempCityName];
            }
        }
        else if(component == 2)
        {
            NSInteger selRow2 = row;
            if (_countyDatasArray.count == 0) {
                selRow2 = 0;
                return;
            }
            else
            {
                if (row > _countyDatasArray.count-1) {
                    selRow2=_countyDatasArray.count;
                }
                NSDictionary *countyDic = _countyDatasArray[selRow2];
                _tempCountyName = countyDic[@"areaname"];
                _tempCountyID = countyDic[@"areaid"];
                if (_townDatasArray.count != 0) {
                    [_townDatasArray removeAllObjects];
                }
                [self loadAreaDataWithAreaID:_tempCountyID andDataType:AreaDataTypeTown];
                cell4.textField.text = [NSString stringWithFormat:@"%@%@%@", _tempProvinceName, _tempCityName, _tempCountyName];
            }
        }
    }
    else if(pickerView.tag == 103) //选择地址：镇，村
    {
        if (component == 0)
        {
            if (_townDatasArray.count == 0) {
                return;
            }
            else
            {
                NSDictionary *townDic = _townDatasArray[row];
                _tempTownName = townDic[@"areaname"];
                _tempTownID = townDic[@"areaid"];
                if (_villageDatasArray.count != 0) {
                    [_villageDatasArray removeAllObjects];
                }
//                [pickerView selectRow:0 inComponent:1 animated:YES];
                [self loadAreaDataWithAreaID:_tempTownID andDataType:AreaDataTypeVillage];
                cell5.textField.text = _tempTownName;
            }
        }
        else if(component == 1)
        {
            NSInteger selRow4 = row;
            if (_villageDatasArray.count == 0) {
                selRow4 = 0;
                return;
            }
            else
            {
                if (row > _villageDatasArray.count-1) {
                    selRow4=_cityDatasArray.count;
                }
                NSDictionary *villageDic = _villageDatasArray[selRow4];
                _tempVillageName = villageDic[@"areaname"];
                _tempVillageID = villageDic[@"areaid"];
                cell5.textField.text = [NSString stringWithFormat:@"%@%@", _tempTownName, _tempVillageName];
            }
        }
    }
    else //选择男女
    {
        if (row == 0) {
            cell2.textField.text = @"男";
            _userGender = @"1";
        }else
        {
            cell2.textField.text= @"女";
            _userGender = @"2";
        }
    }
}

- (void)moveUpView
{
    
    switch ([DeviceInfoClass getCurrentDeviceDetailVersion]) {
        case DeviceInfoVersioniPhone4s:
        {
            [UIView animateWithDuration:0.5 animations:^{
                _tableView.frame = CGRectMake(0, -2, kScreenWidth, kScreenHeight);
            }];
            break;
        }
        /*
        case DeviceInfoVersioniPhone5s:
        {
            [UIView animateWithDuration:0.5 animations:^{
                _tableView.frame = CGRectMake(0, -12, kScreenWidth, kScreenHeight);
            }];
            break;
        }
         */
        default:
            break;
    }
    
}

/*
 *fun:添加单击手势，单击空白处时收起键盘
 */
- (void)addTapRecoginzerToView:(UIView *)aimView
{
    aimView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignTheKeyboard)];
    [aimView addGestureRecognizer:tap];
}

/*
 *fun:收起键盘
 */
- (void)resignTheKeyboard
{
    [self.view endEditing:YES];
    
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight-64);
    }];
     
}


//加载地址数据
- (void)loadAreaDataWithAreaID:(NSString *)areaID andDataType:(AreaDataType)type
{
    SettingTableViewCell *cell4 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; //省 市 镇
    
    SettingTableViewCell *cell5 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];   //县 村
    
    __weak typeof(self) weakSelf = self;
    
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:areaID forKey:@"areaid"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:_access_token];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:_areaURL httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        //        NSLog(@"In changeWorkareaVC: county data:%@", result);
        if ([result[@"response"] isEqualToString:_areaResponse])
        {
            switch (type)
            {
                case AreaDataTypeProvince:
                {
//                    _provinceDatasArray = result[@"arealist"];
                    _provinceDatasArray = [result[@"arealist"] mutableCopy];

                    if (_provinceDatasArray.count != 0) {
                        NSInteger selProvince = [_firstLocationPickerView selectedRowInComponent:0];
                        NSDictionary *provinceDic = _provinceDatasArray[selProvince];
                        _tempProvinceName = provinceDic[@"areaname"];
                        _tempProvinceID = provinceDic[@"areaid"];
                        cell4.textField.text = _tempProvinceName;
                    }
                    
                    break;
                }
                case AreaDataTypeCity:
                {
//                    _cityDatasArray = result[@"arealist"];
                    _cityDatasArray = [result[@"arealist"] mutableCopy];

                    if (_cityDatasArray.count != 0) {
//                        NSInteger selCity = [_firstLocationPickerView selectedRowInComponent:1];
                        NSDictionary *cityDic = _cityDatasArray[0];
                        _tempCityName = cityDic[@"areaname"];
                        _tempCityID = cityDic[@"areaid"];
                        [weakSelf loadAreaDataWithAreaID:_tempCityID andDataType:AreaDataTypeCounty];
                        cell4.textField.text = [NSString stringWithFormat:@"%@%@", _tempProvinceName, _tempCityName];
                    }
                    [_firstLocationPickerView reloadComponent:1];
                    [_firstLocationPickerView selectRow:0 inComponent:1 animated:YES];
                    break;
                }
                case AreaDataTypeCounty:
                {
//                    _countyDatasArray = result[@"arealist"];
                    _countyDatasArray = [result[@"arealist"] mutableCopy];

                    if (_countyDatasArray.count != 0)
                    {
                        NSDictionary *countyDic = _countyDatasArray[0];
                        _tempCountyName = countyDic[@"areaname"];
                        _tempCountyID = countyDic[@"areaid"];
                        [weakSelf loadAreaDataWithAreaID:_tempCountyID andDataType:AreaDataTypeTown];
                        cell4.textField.text = [NSString stringWithFormat:@"%@%@%@", _tempProvinceName, _tempCityName, _tempCountyName];
                    }
                    
                    [_firstLocationPickerView reloadComponent:2];
                    [_firstLocationPickerView selectRow:0 inComponent:2 animated:YES];
                    break;
                }
                case AreaDataTypeTown:
                {
//                    _townDatasArray = result[@"arealist"];
                    _townDatasArray = [result[@"arealist"] mutableCopy];
                    [_secondLocationPickerView reloadComponent:0];
                    
                    /*
                    if (_townDatasArray.count == 0) {
                        return;
                    }
                    else
                    {
                        NSDictionary *townDic = _townDatasArray[0];
                        _tempTownName = townDic[@"areaname"];
                        _tempTownID = townDic[@"areaid"];
                        if (_villageDatasArray.count != 0) {
                            [_villageDatasArray removeAllObjects];
                        }
                        [weakSelf loadAreaDataWithAreaID:_tempTownID andDataType:AreaDataTypeVillage];
                        cell5.textField.text = _tempTownName;
                    }
                     */
                    
                    break;
                }
                case AreaDataTypeVillage:
                {
//                    _villageDatasArray = result[@"arealist"];
                    _villageDatasArray = [result[@"arealist"] mutableCopy];;

                    if (_villageDatasArray.count != 0) {
                        NSDictionary *villageDic = _villageDatasArray[0];
                        _tempVillageName = villageDic[@"areaname"];
                        _tempVillageID = villageDic[@"areaid"];
                        cell5.textField.text = [NSString stringWithFormat:@"%@%@", _tempTownName, _tempVillageName];
                    }
                    [_secondLocationPickerView reloadComponent:1];
                    [_secondLocationPickerView selectRow:0 inComponent:1 animated:YES];
                    break;
                }
                default:
                    break;
            }
        }
        else
        {
            [Config showHUDWithText:@"获取地址错误" andImage:@"error"];
        }
    } failureAction:^{
        [Config showHUDWithText:@"获取地址错误" andImage:@"error"];
    }];
}

- (void)showHUDWithText:(NSString *)str andImage:(NSString *)imgStr
{
    MBProgressHUD *hud = [Config createHUD];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgStr]];
    hud.labelText = str;
    [hud hide:YES afterDelay:1];
}

#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//    [self moveUpView];
    if (textField.tag == baseTextFieldTag+1) //选择性别
    {
        textField.text = @"男";
        _userGender = @"1";
    }
    else if(textField.tag == baseTextFieldTag+2) //选择职业
    {
        if (self.careerArray.count != 0)
        {
            NSInteger selCareer1 = [_careerPickerView selectedRowInComponent:0];
            NSDictionary *careerDic = self.careerArray[selCareer1];
            NSString *careerName1 = careerDic[@"name"];
            NSArray *childCareerArray = careerDic[@"child"];
            NSInteger selCareer2 = [_careerPickerView selectedRowInComponent:1];
            if (childCareerArray.count != 0)
            {
                NSDictionary *childCareerDic = childCareerArray[selCareer2];
                NSString *careerName2 = childCareerDic[@"name"];
                _userCareer = childCareerDic[@"id"];
                NSString *careerName = [NSString stringWithFormat:@"%@ %@", careerName1, careerName2];
                textField.text = careerName;
            }
            else
            {
                textField.text = careerName1;
                _userCareer = careerDic[@"id"];
            }
        }
    }
    else if (textField.tag == baseTextFieldTag+3) //选择住址;省，市，县
    {
        [self moveUpView];
        _villageHaveTouched = NO;
        if (!_provinceHaveTouched)
        {
            if (_provinceDatasArray.count == 0)
            {
                return YES;
            }
            NSDictionary *provinceDic = _provinceDatasArray[0];
            _tempProvinceName = provinceDic[@"areaname"];
            _tempProvinceID = provinceDic[@"areaid"];
            if (_cityDatasArray.count != 0) {
            
            }
            [self loadAreaDataWithAreaID:_tempProvinceID andDataType:AreaDataTypeCity];
            textField.text = _tempProvinceName;
            _provinceHaveTouched = YES;
        }
    }
    else if(textField.tag == baseTextFieldTag+4)  //选择住址;镇，村
    {
        [self moveUpView];
        if (!_villageHaveTouched)
        {
            if (_townDatasArray.count == 0)
            {
                return YES;
            }
//            if (_townDatasArray.count != 0) {
            else{
                NSDictionary *townDic = _townDatasArray[0];
                _tempTownName = townDic[@"areaname"];
                _tempTownID = townDic[@"areaid"];
                [self loadAreaDataWithAreaID:_tempTownID andDataType:AreaDataTypeVillage];
                textField.text = _tempTownName;
            }
            _villageHaveTouched = YES;
        }
        
    }
    
    return YES;
}

- (void)pushToMainVC
{
    MainTabbarVC *mainController = [[MainTabbarVC alloc] init];
    SidePersonMenuVC *sideMenuVC = [[SidePersonMenuVC alloc] init];
    MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:mainController leftDrawerViewController:sideMenuVC];
    [drawerController setMaximumLeftDrawerWidth:LEFTSIDEWIDTH];
    [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    [kkWindow setRootViewController:drawerController];
    [kkWindow makeKeyAndVisible];
}

#pragma mark - 登录后的相关操作
- (void)getUserDetailData{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc] init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"getinfo_member.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"getinfo_member in appdelegate:%@",result);
//        NSDictionary *userInfoDic=[result objectForKey:@"userinfo"];
//        [Login saveUserDetailData:userInfoDic];
        [Login saveUserDetailData:result[@"userinfo"]];
//        [[NSNotificationCenter defaultCenter] postNotificationName:KCLPORTRAITCHANGE object:@YES];
    }failureAction:^{
        
    }];
    
    [self loginOnEaseMob];
}

- (void)loginOnEaseMob{
    
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[Login curLoginBaseUser].huanxin_username password:[Login curLoginBaseUser].huanxin_password completion:^(NSDictionary *loginInfo, EMError *error) {
        if (!error && loginInfo) {
            NSLog(@">>>>>>>>>>>>>>>登陆成功<<<<<<<<<<<<<<<");
        }
    } onQueue:nil];
}
/*
#pragma - mark 选择本地图片上传
- (void)choseImageUpload
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册中选择", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
#pragma mark - csdn example
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    } else if (buttonIndex == 1) {
        UIImagePickerController *imagePickerController = [UIImagePickerController new];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.allowsEditing = YES;
        imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        
        [self presentViewController:imagePickerController animated:YES completion:nil];
    } else {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警告"
                                                                message:@"无法访问摄像头"
                                                               delegate:nil
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles: nil];
            
            [alertView show];
        } else {
            UIImagePickerController *imagePickerController = [UIImagePickerController new];
            imagePickerController.delegate = self;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.allowsEditing = NO;
            imagePickerController.showsCameraControls = YES;
            imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:NULL];
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    _imageToUpload = img;
    [self uploadImage:img];
}

- (void)uploadImage:(UIImage *)image
{
    image = [image fixOrientation];
    NSData *imageData = [Utils compressImage:image];
    
    if (image.size.height > 128 && image.size.width > 128) {
        NSLog(@"execute imageCompress");
        image = [UIImage compressHeaderImageWith:image];
        imageData = [Utils compressImage:image];
    }
    
    NSString *imageEncodeStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSString *imageEncodeStr2 = [imageEncodeStr stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:imageEncodeStr2 forKey:@"file_name"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:_access_token];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"upfile.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"In ChangePersonalInfoVC Upfile:%@", result);
        if ([result[@"response"] isEqualToString:@"upfile"]) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                PersonalPortraitCell *cell = (PersonalPortraitCell *)[_tableView cellForRowAtIndexPath:indexPath];
                [cell setPortraitImage:image];
            });
        }
        else
        {
            NSDictionary *errorDic = result[@"error"];
            [Config showHUDWithText:errorDic[@"text"] andImage:@"error"];
            
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
    
}
 */

@end
